cmake_minimum_required(VERSION 3.8)
project(ocvProject)

# 启用编译数据库的生成
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_program(_PROTOBUF_PROTOC protoc)
find_program(_GRPC_CPP_PLUGIN_EXECUTABLE grpc_cpp_plugin)

find_package(Protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)
find_package(absl CONFIG REQUIRED)

set(gRPC_LIBS
  gRPC::grpc++
  gRPC::grpc++_reflection
  protobuf::libprotobuf
  absl::strings
  absl::synchronization
)

# 查找OpenCV库
find_package(OpenCV 4 REQUIRED)

# 包含OpenCV头文件目录
include_directories(${OpenCV_INCLUDE_DIRS})

set(SERVICE_NAME ocv)

# Proto files
get_filename_component(ocv_proto "${SERVICE_NAME}.proto" ABSOLUTE)
get_filename_component(ocv_proto_path "${ocv_proto}" PATH)
# Generated sources
set(ocv_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/${SERVICE_NAME}.pb.cc")
set(ocv_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/${SERVICE_NAME}.pb.h")
set(ocv_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/${SERVICE_NAME}.grpc.pb.cc")
set(ocv_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/${SERVICE_NAME}.grpc.pb.h")

add_custom_command(
      OUTPUT "${ocv_proto_srcs}" "${ocv_proto_hdrs}" "${ocv_grpc_srcs}" "${ocv_grpc_hdrs}"
      COMMAND ${_PROTOBUF_PROTOC}
      ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
        --cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
        -I "${ocv_proto_path}"
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        "${ocv_proto}"
      DEPENDS "${ocv_proto}")

include_directories(inc ${gRPC_INCLUDE_DIR} ${Protobuf_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})

# 创建一个静态库，包含生成的源文件
add_library(ocv_proto_lib STATIC
    ${ocv_proto_srcs}
    ${ocv_grpc_srcs}
)

# 链接库到静态库
target_link_libraries(ocv_proto_lib
    ${gRPC_LIBS}
)

# 定义服务器和客户端的源文件
set(SERVER_SRC
    ${CMAKE_CURRENT_SOURCE_DIR}/src/ocv_server.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/ocv_service_impl.cpp
)
set(CLIENT_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/ocv_client.cpp)

# 添加服务器和客户端可执行文件，并链接到静态库
add_executable(ocv_server ${SERVER_SRC})
add_executable(ocv_client ${CLIENT_SRC})

# 链接库到可执行文件
target_link_libraries(ocv_server
    ocv_proto_lib
    ${OpenCV_LIBS}
)

target_link_libraries(ocv_client
    ocv_proto_lib
    ${OpenCV_LIBS}
)

enable_testing()
# 添加测试目录
add_subdirectory(test)